﻿Public Class clsSpark
    Private _pos As Drawing.PointF
    Private _vel As Drawing.PointF
    Private _color As Drawing.Color

    Private _timeLiving As Single
    Private _lifeTime As Single

    Private _faded As Boolean

    Private _tcName As String

    Public Sub New(ByVal pos As Drawing.PointF, ByVal vel As Drawing.PointF, ByVal color As Drawing.Color, ByVal lifeTime As Single)
        _pos = pos
        _vel = vel
        _color = color
        _lifeTime = lifeTime
        _faded = False

        _tcName = clsSimTime.AddTimeControl("spark")
    End Sub

    Public ReadOnly Property Faded
        Get
            Return _faded
        End Get
    End Property

    Public Sub Draw(ByRef g As Drawing.Graphics)
        If _faded Then Return

        ' # Render

        ' Fading
        Dim p As New Drawing.Pen(Drawing.Color.FromArgb(((_lifeTime - _timeLiving) / _lifeTime) * 255, _color))
        Dim length As Single = Math.Sqrt(Math.Pow(_vel.X, 2) + Math.Pow(_vel.Y, 2)) * 0.2

        Dim angle As Single = Math.Atan2(-_vel.Y, _vel.X)

        Dim x1, y1, x2, y2 As Single
        x1 = _pos.X + Math.Cos(angle) * (length / 2.0)
        y1 = _pos.Y + Math.Sin(angle) * (length / 2.0)
        x2 = _pos.X - Math.Cos(angle) * (length / 2.0)
        y2 = _pos.Y - Math.Sin(angle) * (length / 2.0)

        g.DrawLine(p, x1, y1, x2, y2)

        ' # Update
        Dim timeDiff As Double = clsSimTime.GetTimeDifference(_tcName)
        _pos.X += timeDiff * _vel.X * 2
        _pos.Y -= timeDiff * _vel.Y * 2
        _vel.X += clsSim.Wind * timeDiff
        _vel.Y += clsSim.GRAVITY * timeDiff * 4
        _timeLiving += timeDiff

        If _timeLiving >= _lifeTime Then
            Fade()
        End If
    End Sub

    Private Sub Fade()
        _faded = True
        clsSimTime.RemoveTimeControl(_tcName)
    End Sub
End Class
